import 'package:flutter_svg/svg.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:sleep/help_style.dart';
import 'package:sleep/model/person/person.dart';
import 'package:sleep/model/setting/setting.dart';
import 'package:sleep/page/blue/blue_scan_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:sleep/page/fatigue/comp/chart_detail.dart';
import 'package:sleep/page/setting/setting.dart';
import 'package:sleep/provider/chat_config_provider.dart';
import 'package:sleep/provider/db_provider.dart';
import 'package:sleep/provider/wave_deatil_provider/fatigue_detail_provider.dart';
import 'package:sleep/provider/wave_deatil_provider/sleep_detail_provider.dart';
import 'package:sleep/provider/wave_deatil_provider/wave_provider.dart';

enum UserType { sleep, fatigue }

class UserPage extends StatefulWidget {
  final String title;
  final UserType type;
  final Person? person;

  UserPage({Key? key, this.title = "填写个人信息", required this.type, this.person})
      : super(key: key);

  @override
  State<UserPage> createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> {
  late List<_UserInputModel> inputUser;
  late Gender gender;
  double? value;
  double? multipe;

  @override
  void initState() {
    inputUser = [
      ...inputUserBase(
        name: widget.person?.name,
        age: widget.person?.age,
      )
    ];
    gender = widget.person?.gender ?? Gender.male;
    if (widget.type == UserType.sleep) {
      inputUser.addAll(
          filterMessage(height: widget.person?.height, l: widget.person?.l));
    }

    super.initState();
  }

  jumpClick(
    BuildContext context,
    WidgetRef ref,
  ) {
    bool isFinish = true;
    for (final e in inputUser) {
      if (e.need && e.value == null && e.defaultValue == null) {
        EasyLoading.showInfo(e.errorMessage);
        isFinish = false;
        break;
      }
    }

    if (value == null) {
      EasyLoading.showError("need value");
      return;
    }
    if (isFinish) {
      Map<String, Object?> userMap = {};
      for (final e in [...inputUser]) {
        userMap[e.key] = e.value ?? e.defaultValue;
      }
      userMap['gender'] = gender == Gender.male ? 'male' : 'female';

      userMap['value'] = value;
      userMap['multipe'] = multipe;

      final db = ref.read(dbProvider);

      db.savePerson(Person.fromJson(userMap),
          widget.type == UserType.fatigue ? kFatiguePerson : kSleepPerson);
      if (widget.person != null) {
        Navigator.of(context).pop();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          backgroundColor: HelpStyle.backgroundColor,
          elevation: 0,
          centerTitle: true,
          actions: [
            IconButton(
                padding: EdgeInsets.zero,
                onPressed: () {
                  Navigator.of(context).push(
                    MaterialPageRoute(
                        builder: (context) => Setting(
                            type: widget.type == UserType.sleep
                                ? SettingType.sleep
                                : SettingType.fatuige)),
                  );
                },
                icon: Icon(
                  Icons.settings,
                  color: HelpStyle.primarycolor,
                )),
            IconButton(
                padding: EdgeInsets.zero,
                onPressed: () {
                  Navigator.of(context).push(
                    MaterialPageRoute(builder: (context) => BlueScanScreen()),
                  );
                },
                icon: Icon(
                  Icons.bluetooth,
                  color: HelpStyle.primarycolor,
                )),
          ],
          leading: widget.person == null
              ? const SizedBox()
              : IconButton(
                  icon: Icon(Icons.arrow_back, color: Colors.white),
                  onPressed: () => Navigator.of(context).pop(),
                ),
          title: Text(
            'User Data',
            style: HelpStyle.titleStyle3,
          )),
      body: Padding(
        padding: const EdgeInsets.only(left: 12.0, right: 12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(
                    left: 12.0, right: 8.0, top: 10, bottom: 8.0),
                child: ListView(
                  children: [
                    Container(
                      decoration: HelpStyle.decoration,
                      padding: EdgeInsets.all(HelpStyle.cellMargin),
                      child: Column(
                        children: [
                          ...inputUser.map(((e) => input(e))),
                          genderWidget(),
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 12,
                    ),
                    userSampler(),
                  ],
                ),
              ),
            ),
            SafeArea(
              bottom: true,
              child: jumBtn(context),
            ),
            const SizedBox(
              height: 12,
            ),
          ],
        ),
      ),
    );
  }

  Widget jumBtn(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 18.0, right: 18.0),
      child: Consumer(builder: (
        BuildContext context,
        WidgetRef ref,
        Widget? child,
      ) {
        return TextButton(
            style: ButtonStyle(
                backgroundColor:
                    MaterialStateProperty.all(HelpStyle.primarycolor)),
            onPressed: () {
              jumpClick(
                context,
                ref,
              );
            },
            child: SizedBox(
                width: double.maxFinite,
                child: Text(
                  'Next',
                  textAlign: TextAlign.center,
                  style: HelpStyle.titleStyle3.copyWith(color: Colors.white),
                )));
      }),
    );
  }

  Widget userSampler() {
    return Container(
      padding: EdgeInsets.all(HelpStyle.margin),
      decoration: HelpStyle.decoration,
      child: Stack(
        children: [
          Positioned(
              left: 0,
              right: 0,
              child: Text(
                widget.type == UserType.sleep
                    ? 'Deep Breathing Test'
                    : 'Blink Test (Eyes fully open to fully closed slowly)',
                style: HelpStyle.smallStyle,
              )),
          if (widget.type == UserType.fatigue) fatigueTipImage(),
          if (widget.type == UserType.sleep) sleepTipImage(),
          if (widget.type == UserType.fatigue) fatigueText(),
          if (widget.type == UserType.sleep) sleepText(),
          Column(
            children: [
              const SizedBox(
                height: 220,
              ),
              widget.type == UserType.fatigue ? fatigueChat() : sleepChat(),
            ],
          ),
        ],
      ),
    );
  }

  Widget fatigueTipImage() {
    return Positioned(
        height: 150,
        left: 0,
        right: 0,
        top: 30,
        child: Image(image: AssetImage('assets/seye.jpg')));
    // SvgPicture.asset('assets/seye.jpg')
  }

  Widget sleepTipImage() {
    return Positioned(
        top: -150,
        left: 0,
        right: 0,
        child: SvgPicture.asset('assets/breathing.svg'));
  }

  fatigueText() {
    return Consumer(builder: (context, ref, child) {
      final fatigue = ref.watch(fatigueDetailProvider);
      final setting = ref.watch(dbProvider).fatuigeSetting();
      if (fatigue.wave?.vhight != null) {
        value = fatigue.wave!.vhight;
        multipe = setting.multiple;
      }

      return Positioned(
          top: 180,
          child: Text(
            "${fatigue.wave?.vhight.toStringAsFixed(2) ?? ""}V",
            style:
                HelpStyle.titleStyle3.copyWith(color: HelpStyle.primarycolor),
          ));
    });
  }

  sleepText() {
    return Consumer(builder: (context, ref, child) {
      final sleep = ref.watch(sleepDetailProvider);
      final setting = ref.watch(dbProvider).sleepSetting();
      if (sleep.wave?.vhight != null) {
        value = sleep.wave!.vhight;

        multipe = setting.multiple;
      }

      return Positioned(
          top: 190,
          child: Text(
            "${sleep.wave?.vhight.toStringAsFixed(2) ?? ""}V",
            style:
                HelpStyle.titleStyle3.copyWith(color: HelpStyle.primarycolor),
          ));
    });
  }

  fatigueChat() {
    return Consumer(
      builder: (context, ref, child) {
        final fatigue = ref.watch(fatigueProvider);
        final chatConfig = ref.watch(chatConfigProvider).fatigueChat;

        return FaDetailChart(
            aspectRatio: 2,
            maxX: chatConfig.maxX,
            minX: chatConfig.minX,
            mimResolution: chatConfig.mimResolution,
            maxY: chatConfig.maxY,
            minY: chatConfig.minY,
            spots: fatigue.spots);
      },
    );
  }

  sleepChat() {
    return Consumer(
      builder: (context, ref, child) {
        WaveDataNotifier sleep = ref.watch(sleepProvider);
        final chatConfig = ref.watch(chatConfigProvider).sleepChat;
        return FaDetailChart(
            aspectRatio: 2,
            maxX: chatConfig.maxX,
            minX: chatConfig.minX,
            mimResolution: chatConfig.mimResolution,
            maxY: chatConfig.maxY,
            minY: chatConfig.minY,
            spots: sleep.spots);
      },
    );
  }

  Widget input(_UserInputModel model) {
    return Container(
      margin: EdgeInsets.only(left: 8, right: 18, top: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(model.title, style: HelpStyle.contextStyle),
          const SizedBox(height: 6),
          TextField(
              onChanged: ((value) {
                if (model.type == TextInputType.number) {
                  model.value = double.tryParse(value);
                } else {
                  model.value = value;
                }
              }),
              controller: TextEditingController(
                  text: model.value?.toString() ??
                      model.defaultValue?.toString()),
              style: HelpStyle.titleStyle,
              keyboardType: model.type,
              decoration: InputDecoration(
                fillColor: HelpStyle.backgroundColor,
                labelStyle: MaterialStateTextStyle.resolveWith(
                    (states) => HelpStyle.titleStyle),
                filled: true,
                isCollapsed: true,
                border: const OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(25))),
                contentPadding:
                    const EdgeInsets.symmetric(horizontal: 18, vertical: 8),
              )),
        ],
      ),
    );
  }

  genderWidget() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Row(
        children: [
          Expanded(
            child: genderItem(Gender.male),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: genderItem(Gender.female),
          )
        ],
      ),
    );
  }

  genderItem(Gender type) {
    final isSect = type == gender;
    final textColor =
        isSect ? HelpStyle.backgroundColor : HelpStyle.primarycolor;
    final backColor =
        isSect ? HelpStyle.primarycolor : HelpStyle.backgroundColor;
    final text = type == Gender.male ? "male" : "female";
    return TextButton(
      onPressed: () {
        setState(() {
          gender = type;
        });
      },
      style: ButtonStyle(backgroundColor: MaterialStateProperty.all(backColor)),
      child: Text(
        text,
        style: HelpStyle.contextStyle.copyWith(color: textColor),
      ),
    );
  }

  List<_UserInputModel> inputUserBase({
    String? name,
    double? age,
  }) {
    return [
      _UserInputModel(
        title: 'Name',
        key: "name",
        type: TextInputType.text,
        need: true,
        defaultValue: name,
        errorMessage: 'need name',
      ),
      _UserInputModel(
        title: 'Age',
        key: 'age',
        defaultValue: age,
        type: TextInputType.number,
        need: true,
        errorMessage: 'need age',
      ),
    ];
  }

  List<_UserInputModel> filterMessage({double? height, double? l}) {
    return [
      _UserInputModel(
        title: 'Height (m)',
        key: 'height',
        type: TextInputType.number,
        need: true,
        defaultValue: height,
        errorMessage: 'need height',
      ),
      _UserInputModel(
        title: '△L (m)',
        key: 'l',
        type: TextInputType.number,
        defaultValue: l,
        need: true,
        errorMessage: 'need △L',
      ),
    ];
  }
}

class _UserInputModel {
  final String title;
  final TextInputType type;
  final Object? defaultValue;
  final bool need;
  final String errorMessage;
  Object? value;
  final String key;
  _UserInputModel({
    this.defaultValue,
    this.need = false,
    required this.errorMessage,
    required this.title,
    required this.type,
    required this.key,
  });
}
